package com.lyhengtongwl.zqsnews.ui.fragment.forward;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.NewsAdapter;
import com.lyhengtongwl.zqsnews.base.LazyLoadBaseFragment;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsEntity;
import com.lyhengtongwl.zqsnews.entity.TJTopScrollEntity;
import com.lyhengtongwl.zqsnews.entity.UserLocationBo;
import com.lyhengtongwl.zqsnews.imageLoader.GlideImageLoader;
import com.lyhengtongwl.zqsnews.NewsInterface.GDLocation;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.NoVerifyTask;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.fragment.NewsByForwardFragment;
import com.lyhengtongwl.zqsnews.utils.UpClickCountUtils;
import com.lyhengtongwl.zqsnews.ui.activity.MainActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebCommonActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebDetailActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebGLActivity;
import com.lyhengtongwl.zqsnews.utils.GPSUtils;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.TTAdManagerHolder;
import com.lyhengtongwl.zqsnews.widget.ScrollTextView;
import com.lyhengtongwl.putorefresh.BaseBothListener;
import com.lyhengtongwl.putorefresh.PullToBothLayout;
import com.lyhengtongwl.putorefresh.ViewStatus;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import retrofit2.Response;

import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;


@SuppressLint("ValidFragment")
public class ForwardFragments extends LazyLoadBaseFragment {
    private String newsType;
    @BindView(R.id.ll_top)
    LinearLayout ll_top;
    @BindView(R.id.mBanner)
    Banner mBanner;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;
    @BindView(R.id.vf_notice_scroll)
    ScrollTextView vf_notice_scroll;
    private List<NewsEntity> list = new ArrayList<>();
    private int page = 1;//默认第一页
    private boolean isRefresh = true;//默认下拉刷新
    private NewsAdapter newsAdapter = null;
    private static String title;
    private static String imgUrl;
    private static String articleId;
    private String cityCode = "";//城市编码
    private AMapLocation mapLocation = null;

    private TTNativeExpressAd mTTAd;


    //测试预加载
//    private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;

    public ForwardFragments(String newsType) {
        this.newsType = newsType;
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_forward;
    }

    @Override
    protected void initView(View rootView) {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        if ("1".equals(newsType)) {
            ll_top.setVisibility(View.VISIBLE);
            setBanner();
            setScroll();
        } else {
            ll_top.setVisibility(View.GONE);
        }
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("forward", "onScrolled: 开始加载");
                if (dy > 0) {//表示手势向上
                    int visibleItemCount = manager.getChildCount();    //得到显示屏幕内的list数量
                    int totalItemCount = manager.getItemCount();    //得到list的总数量
                    int pastVisiblesItems = manager.findFirstVisibleItemPosition();//得到显示屏内的第一个list的位置数position
                    isRefresh = false;
                    Log.e("forward", "onScrolled: 开始加载"+visibleItemCount+"==="+pastVisiblesItems+"=="+totalItemCount);
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        loadData();
                    }
                } else {
                    isRefresh = true;
                }
            }
        });
        setListen();
    }

    private void setAdapter() {
        if (newsAdapter == null) {
            newsAdapter = new NewsAdapter(getActivity(), list, newsType);
            recyclerView.setAdapter(newsAdapter);
            newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (!"17".equals(list.get(position).getTypeId())) {
                        String imgUrl = list.get(position).getUrl();
                        String title = list.get(position).getTitle();
                        String articleReadId = list.get(position).getArticleId();
                        String articleId = list.get(position).getRandomCode();
                        String mDns = list.get(position).getmDns();
                        Bundle bundle = new Bundle();
                        bundle.putString("imgUrl", imgUrl);
                        bundle.putString("articleId", articleId);
                        bundle.putString("title", title);
                        bundle.putString("articleReadId", articleReadId);
//                        bundle.putString("dns", mDns);
                        NewsWebDetailActivity.forward(getActivity(), bundle);
                    } else {//表示阅读广告
                        startActivity(new Intent(getActivity(), NewsWebCommonActivity.class).putExtra("url", list.get(position).getContentUrl()));
                        upCount(position);
                    }
                }
            });
        } else {
            newsAdapter.notifyDataSetChanged();
        }
    }

    //阅读广告进行上传次数
    private void upCount(int position) {
        Task.getApiService().articleClick(Integer.parseInt(list.get(position).getArticleId()), Integer.parseInt(list.get(position).getTypeId())).enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //设置banner图
    private void setBanner() {
        List<String> url = new ArrayList<>();//图片url
        List<String> linkUrl = new ArrayList<>();//图片linkUrl
        List<String> action = new ArrayList<>();//跳转地方  0 ： 普通网页  1：收徒攻略
        List<String> adName = new ArrayList<>();//banner名字
        JSONArray banner = NewsByForwardFragment.adArray;
        if (banner != null && banner.size() > 0) {
            for (int i = 0; i < banner.size(); i++) {
                url.add(JSON.parseObject(banner.getString(i)).getString("adFile"));
                linkUrl.add(JSON.parseObject(banner.getString(i)).getString("adUrl"));
                action.add(JSON.parseObject(banner.getString(i)).getInteger("action") + "");
                adName.add(JSON.parseObject(banner.getString(i)).getString("adName"));
            }
        }
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        GlideImageLoader glideImageLoader = new GlideImageLoader();
        //设置图片加载器
        mBanner.setImageLoader(glideImageLoader);
        //设置图片集合
        mBanner.setImages(url);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置动画
        mBanner.setBannerAnimation(Transformer.Default);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.start();
        mBanner.startAutoPlay();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                UpClickCountUtils.getInstance(getActivity()).upClick("banner", adName.get(position));
                if (linkUrl.size() > 0 && !linkUrl.get(position).equals("")) {
                    switch (action.get(position)) {
                        case "0":
                            startActivity(new Intent(getActivity(), NewsWebCommonActivity.class).putExtra("url", linkUrl.get(position)));
                            break;
                        case "1":
                            ((MainActivity) getActivity()).getTabLayout(1).setCurrentTab(1);
//                            startActivity(new Intent(getActivity(), NewsWebGLActivity.class).putExtra("url", linkUrl.get(position)));
                            break;
                        case "2":
                            startActivity(new Intent(getActivity(), NewsWebGLActivity.class).putExtra("url", linkUrl.get(position)));
                            break;
                        case "3":
                            startActivity(new Intent(getActivity(), NewsWebGLActivity.class).putExtra("url", linkUrl.get(position))
                                    .putExtra("isDefault", "true")
                            );
                            break;
                    }
                }
            }
        });
    }

    //设置上下滚动标签
    private void setScroll() {
        JSONArray scrollArray = NewsByForwardFragment.moneyMsgArray;
        List<TJTopScrollEntity> demographicsList = new ArrayList<>();

        if (scrollArray != null && scrollArray.size() > 0) {
            for (int i = 0; i < scrollArray.size(); i++) {
                TJTopScrollEntity tjTopScrollEntity = new TJTopScrollEntity();
                tjTopScrollEntity.setContent(JSON.parseObject(scrollArray.getString(i)).getString("nameStr"));
                tjTopScrollEntity.setMoney(JSON.parseObject(scrollArray.getString(i)).getString("moneyStr"));
                tjTopScrollEntity.setState(JSON.parseObject(scrollArray.getString(i)).getString("timeStr"));
                demographicsList.add(tjTopScrollEntity);
            }
        }
        vf_notice_scroll.setList(demographicsList);
        vf_notice_scroll.startScroll();
    }

    private void setListen() {

        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                isRefresh = true;
                page = 1;
                loadData();
            }

            @Override
            public void loadMore() {
                isRefresh = false;
                page++;
                loadData();
            }
        });
    }

    /**
     * 只进行刷新一次
     */
    @Override
    protected void requestData() {
        super.requestData();
        if ("2".equals(newsType)) {
            //需要获取权限
            getLocationPermission();
        } else {
            loadData();
        }
//        loadListAd();
    }

    /**
     * 获取定位权限
     */
    private void getLocationPermission() {
        int flag = ActivityCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION);
        if (flag != PackageManager.PERMISSION_GRANTED) {
            ForwardFragments.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            getLocation();
        }

    }

    //获取位置信息
    private void getLocation() {
        //获取城市编码
//            loadData();
        pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        GPSUtils.getInstance(getActivity()).getLocation(new GDLocation() {
            @Override
            public void onSuccess(AMapLocation aMapLocation) {
                cityCode = aMapLocation.getCityCode();
                mapLocation = aMapLocation;
                loadData();
            }

            @Override
            public void onFail(int code) {
                //获取位置信息失败
                pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {//选择了“始终允许”
                    getLocation();
                } else {//权限被拒绝
                    pullToBothLayout.showView(ViewStatus.ERROR_STATUS);
                    pullToBothLayout.getView(ViewStatus.ERROR_STATUS).findViewById(R.id.tv_withDrawNow).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //弹出开启权限
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(getActivity());
                        }
                    });
                }
            }
        }

    }
    //加载数据

    private void loadData() {
        if (isRefresh)
            pullToBothLayout.showView(ViewStatus.LOADING_STATUS);
        NoVerifyTask.getApiService().getArticle(page, newsType, cityCode).enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                if (("1").equals(response.body().getCode())) {
                    JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                    if (isRefresh) {
                        //表示下拉刷新
                        if (jsonArray.size() > 0) {
                            pullToBothLayout.showView(ViewStatus.CONTENT_STATUS);
                            list.clear();
                            for (int i = 0; i < jsonArray.size(); i++) {
                                NewsEntity newsEntity = new NewsEntity();
                                newsEntity.setMoney(jsonArray.getJSONObject(i).getInteger("incomeNum") + "");
                                newsEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                                newsEntity.setUrl(jsonArray.getJSONObject(i).getString("image"));
                                newsEntity.setArticleId(jsonArray.getJSONObject(i).getInteger("id") + "");
                                newsEntity.setTypeId(jsonArray.getJSONObject(i).getInteger("typeId") + "");
                                newsEntity.setmDns(jsonArray.getJSONObject(i).getString("remark"));
                                newsEntity.setContentUrl(jsonArray.getJSONObject(i).getString("contentUrl"));
                                newsEntity.setRandomCode(jsonArray.getJSONObject(i).getString("randomCode"));
                                list.add(newsEntity);
                            }
//                        newsAdapter.notifyDataSetChanged();
                            setAdapter();
                        } else {
                            pullToBothLayout.showView(ViewStatus.EMPTY_STATUS);
                        }
                        pullToBothLayout.finishRefresh();

                    } else {
                        if (jsonArray.size() > 0) {
                            //上拉加载
                            for (int i = 0; i < jsonArray.size(); i++) {
                                NewsEntity newsEntity = new NewsEntity();
                                newsEntity.setMoney(jsonArray.getJSONObject(i).getInteger("incomeNum") + "");
                                newsEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                                newsEntity.setUrl(jsonArray.getJSONObject(i).getString("image"));
                                newsEntity.setArticleId(jsonArray.getJSONObject(i).getInteger("id") + "");
                                newsEntity.setTypeId(jsonArray.getJSONObject(i).getInteger("typeId") + "");
                                newsEntity.setmDns(jsonArray.getJSONObject(i).getString("remark"));
//                            newsEntity.setContent(jsonArray.getJSONObject(i).getString("content"));
                                newsEntity.setContentUrl(jsonArray.getJSONObject(i).getString("contentUrl"));
                                newsEntity.setRandomCode(jsonArray.getJSONObject(i).getString("randomCode"));
                                list.add(newsEntity);
                            }
//                        newsAdapter.notifyDataSetChanged();
                            setAdapter();
                        }
                        pullToBothLayout.finishLoadMore();
                    }

                }
            }

            @Override
            protected void onFailure(Throwable t) {
                pullToBothLayout.finishRefresh();
                pullToBothLayout.finishLoadMore();
            }
        });
    }

    /**
     * 加载feed广告
     */
    private void loadListAd() {
        TTAdNative mTTAdNative;
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        mTTAdNative = ttAdManager.createAdNative(getActivity());
        //申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(getActivity());
        //feed广告请求类型参数
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId("901121253") //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(640, 320) //期望个性化模板广告view的size,单位dp
                .setImageAcceptedSize(640, 320) //这个参数设置即可，不影响个性化模板广告的size
                .build();
        //加载广告
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e("加载视频流广告", "onError: " + message + "***" + code);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                mTTAd = ads.get(0);
                bindAdListener(mTTAd);
                mTTAd.render();//调用render开始渲染广告
            }
        });
    }

    //绑定广告行为
    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
            }

            @Override
            public void onAdShow(View view, int type) {
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                Log.e("加载视频流广告", "onRenderSuccess: 返回成功");
                //返回view的宽高 单位 dp
                newsAdapter.addHeaderView(view);
            }
        });
        //dislike设置
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        //可选，下载监听设置
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            }

            @Override
            public void onInstalled(String fileName, String appName) {
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            }
        });
    }

    //每次都去上传位置信息
    @Override
    protected void requestDataAutoRefresh() {
        super.requestDataAutoRefresh();
        if (newsType.equals("2")) {
            String userId = SPUtils.get(App.getContext(), "userId", "") + "";
            if (!userId.equals("") && mapLocation != null) {
                double latitude = mapLocation.getLatitude();
                double longitude = mapLocation.getLongitude();
                String currcity = mapLocation.getCity();
                String district = mapLocation.getDistrict();
                String currnation = mapLocation.getCountry();
                String currprovince = mapLocation.getProvince();
                UserLocationBo userLocationBo = new UserLocationBo();
                userLocationBo.setAppid(SPUtils.get(App.getContext(), "uniqueIdentifier", "android") + "");
                userLocationBo.setCurrcity(currcity);
                userLocationBo.setCurrdistrict(district);
                userLocationBo.setCurrnation(currnation);
                userLocationBo.setCurrprovince(currprovince);
                userLocationBo.setLatitude(latitude);
                userLocationBo.setLongitude(longitude);
                userLocationBo.setLocation(mapLocation.getAddress());
                userLocationBo.setUserid(userId);
                upLoadLocation(userLocationBo);
            }
        }
    }

    private void upLoadLocation(UserLocationBo userLocationBo) {
        Task.getApiService().upLoadLocation(userLocationBo).enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
//                Log.e("uploadLocation", "上传位置信息！" );
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });

    }
}
